﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;

namespace Nivdal
{

    public partial class WriteForumPost : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                Response.Redirect("~/Default.aspx");
            OnlineUser ou = (OnlineUser)Session["User"];
            //CultureInfo Cult = ResolveCulture();

            //if ((Cult != null) &&(Cult.TextInfo.IsRightToLeft))
            //if (ou.IsRTL())
            //{
            //    const string crlf = "\r\n";
            //    string js = "<script type='text/javascript'>" + crlf +
            //        "{" + crlf +
            //            "<script type=text/javascript>" + crlf +

            //    "Sys.Application.add_load(function () {" + crlf +

            //        "var Threadeditor = $find(<%= Threadeditor.ClientID %>);" + crlf +
            //        "var editPanel = Threadeditor.get_editPanel();" + crlf +

            //        "editPanel._setActive_saved = editPanel._setActive;" + crlf +
            //        "editPanel._setActive = function () {" + crlf +
            //            "if (this.get_activeMode() == AjaxControlToolkit.HTMLEditor.ActiveModeType.Design) {" + crlf +
            //                "var designPanel = this.get_activePanel();" + crlf +
            //                "if (this._eAfter == null) {" + crlf +
            //                    "designPanel._doc.body.style.direction = rtl;" + crlf +
            //                "}" + crlf +
            //            "}" + crlf +
            //            "this._setActive_saved();" + crlf +
            //        "};" + crlf +
            //    "});" + crlf +
            //    "</script>";
            //    Page.RegisterStartupScript("js", js);

            //}


            // TextHelpLabel.Text = GlobalFunctions.EditorHelp();

            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.WriteForumPost_Title;
            //this.Title = Resources.Resource.WriteForumPost_Title + " - " + GND.ReturnAppTitle();
            
            if (ou.TeamId == "Null")
                Response.Redirect("~/GeneralMessage.aspx?MessageString=M74ggdizz5wfeh");

            string ThreadId = null;
            if (Request.QueryString["ThreadId"] != null)
            {
                ThreadId = Request.QueryString["ThreadId"].ToString();
                ThreadIdHiddenField.Value = ThreadId;
            }
            else
                Response.Redirect("~/ForumHomePage.aspx");
            
            string ReplyToPost = null;
            if (Request.QueryString["ReplyToPost"] != null)
            {
                ReplyToPost = Request.QueryString["ReplyToPost"].ToString();
                ReplyToPostHiddenField.Value = ReplyToPost;
                if (!GND.ReadNivdalBoolData("@UserId", "@PostId", "@ThreadId", "Nivdal_ForumCanUserSeePost", ou.UserId, ReplyToPost, ThreadId))
                    Response.Redirect("~/ForumHomePage.aspx");
            }
            else
            {
                ReplyToPostHiddenField.Value = "NULL";
            }
            
            string ReplyToUser = null;
            if (Request.QueryString["ReplyToUser"] != null)
            {
                this.AsReplyToHyperLink.Visible = true;
                this.ReplyToLabel.Visible = true;
                this.OriginalMessageLabel.Visible = true;
                ReplyToUser = Request.QueryString["ReplyToUser"].ToString();
                this.AsReplyToHyperLink.Text = (GND.ReadNivdalStringData("@UserId", "Nivdal_GetUserNameById", ReplyToUser));
                this.AsReplyToHyperLink.NavigateUrl = "UserPage.aspx?Id=" + ReplyToUser;
                this.OriginalMessageLabel.Text = GlobalFunctions.EncodeHtmlFromText((GND.ReadNivdalStringData("@PostId", "Nivdal_ForumGetPostTextById", ReplyToPost)));
                ReplyToUserHiddenField.Value = ReplyToUser;
            }
            else
                ReplyToUserHiddenField.Value = "NULL";

            //Response.Write (GND.ReadNivdalBoolData("@UserId", "@ThreadId", "Nivdal_ForumCanUserSeeThread", UsrId, ThreadId));
            //Response.Write (GND.ReadNivdalBoolData("@UserId", "@PostId", "@ThreadId", "Nivdal_ForumCanUserSeePost", UsrId, ReplyToPost, ThreadId));


            if (!GND.ReadNivdalBoolData("@UserId", "@ThreadId", "Nivdal_ForumCanUserSeeThread", ou.UserId, ThreadId))
                Response.Redirect("~/ForumHomePage.aspx");


        }

        //public static CultureInfo ResolveCulture()
        //{
        //    string[] languages = HttpContext.Current.Request.UserLanguages;
        //    if (languages == null || languages.Length == 0)
        //        return null;
        //    try
        //    {
        //        string language = languages[0].ToLowerInvariant().Trim();
        //        return System.Globalization.CultureInfo.CreateSpecificCulture(language);
        //    }
        //    catch (ArgumentException)
        //    {
        //        return null;
        //    }
        //}

        protected void AddThread_Click(object sender, EventArgs e)
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            this.MessageLabel.Text = "";
            this.MessageLabel.ForeColor = System.Drawing.Color.Green;
            string ThreadId = ThreadIdHiddenField.Value;
            string ReplyToPost = ReplyToPostHiddenField.Value;
            string ReplyToUser = ReplyToUserHiddenField.Value;
            
            String PostText = this.Threadeditor.Text.Trim();
            
            if (PostText.Length > 4000 || PostText.Length < 1)
            {
                this.MessageLabel.ForeColor = System.Drawing.Color.Red;
                this.MessageLabel.Text = (Resources.Resource.WriteForumPost_ErrorMessage);
            }
            else //input is good
            {

                string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
                System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
                dbCommand.CommandText = "Nivdal_ForumAddNewPost";
                dbCommand.CommandType = CommandType.StoredProcedure;
                dbCommand.Connection = dbConnection;

                SqlParameter dbParam_PostedBy = new SqlParameter();
                dbParam_PostedBy.ParameterName = "@PostedBy";
                dbParam_PostedBy.Value = ou.UserId;
                dbParam_PostedBy.DbType = DbType.String;
                dbCommand.Parameters.Add(dbParam_PostedBy);

                if (ReplyToPost != "NULL")
                {
                    SqlParameter dbParam_ReplyToPost = new SqlParameter();
                    dbParam_ReplyToPost.ParameterName = "@ReplyToPost";
                    dbParam_ReplyToPost.Value = ReplyToPost;
                    dbParam_ReplyToPost.DbType = DbType.String;
                    dbCommand.Parameters.Add(dbParam_ReplyToPost);
                }

                if (ReplyToUser != "NULL")
                {
                    SqlParameter dbParam_ReplyToUser = new SqlParameter();
                    dbParam_ReplyToUser.ParameterName = "@ReplyToUser";
                    dbParam_ReplyToUser.Value = ReplyToUser;
                    dbParam_ReplyToUser.DbType = DbType.String;
                    dbCommand.Parameters.Add(dbParam_ReplyToUser);
                }

                SqlParameter dbParam_PostText = new SqlParameter();
                dbParam_PostText.ParameterName = "@PostText";
                dbParam_PostText.Value = GlobalFunctions.EncodeHtmlFromText(PostText);
                dbParam_PostText.DbType = DbType.String;
                dbCommand.Parameters.Add(dbParam_PostText);

                SqlParameter dbParam_PostOriginal = new SqlParameter();
                dbParam_PostOriginal.ParameterName = "@OriginalText";
                dbParam_PostOriginal.Value = PostText;
                dbParam_PostOriginal.DbType = DbType.String;
                dbCommand.Parameters.Add(dbParam_PostOriginal);

                SqlParameter dbParam_ThreadId = new SqlParameter();
                dbParam_ThreadId.ParameterName = "@ThreadId";
                dbParam_ThreadId.Value = ThreadId;
                dbParam_ThreadId.DbType = DbType.Decimal;
                dbParam_ThreadId.Size = 12;
                dbCommand.Parameters.Add(dbParam_ThreadId);

                SqlParameter dbParam_Answer = new SqlParameter();
                dbParam_Answer.ParameterName = "@Answer";
                dbParam_Answer.Value = "";
                dbParam_Answer.DbType = DbType.String;
                dbParam_Answer.Direction = ParameterDirection.Output;
                dbParam_Answer.Size = 64;
                dbCommand.Parameters.Add(dbParam_Answer);

                SqlParameter dbParam_PostId = new SqlParameter();
                dbParam_PostId.ParameterName = "@PostId";
                dbParam_PostId.Value = "";
                dbParam_PostId.DbType = DbType.Decimal;
                dbParam_PostId.Direction = ParameterDirection.Output;
                dbParam_PostId.Size = 12;
                dbCommand.Parameters.Add(dbParam_PostId);

                try
                {

                    dbConnection.Open();
                    dbCommand.ExecuteScalar();
                    if (dbParam_ThreadId.Value.ToString() != "0")
                        Response.Redirect("ThreadDetails.aspx?ThreadId=" + ThreadId + "&PostId=" + dbParam_PostId.Value.ToString() +
                            "&Answer=" + dbParam_Answer.Value.ToString());
                    else
                        this.MessageLabel.Text = dbParam_Answer.Value.ToString();
                }
                catch (Exception SQLDBException)
                {
                    this.MessageLabel.Text = Convert.ToString(SQLDBException);
                }

                finally
                {
                    dbConnection.Close();
                }
            }

        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            this.PreviewLabel.Text = GlobalFunctions.EncodeHtmlFromText(this.Threadeditor.Text.Trim());
        }

        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }

    }
}